package com.aaa.common.util;

import com.aliyun.oss.ClientBuilderConfiguration;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.common.auth.CredentialsProvider;
import com.aliyun.oss.common.auth.DefaultCredentialProvider;
import com.aliyun.oss.common.comm.SignVersion;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * @ FileName: OssUtil
 * @ Description:
 * @ Author:  STB
 * @ CreateTime: 2025/9/22 0022 16:27
 * @ Version: 1.0.0
 */
public class OssUtil {
    //定义常量
    private static  final  String END_POINT = "https://oss-cn-wuhan-lr.aliyuncs.com";
    private static  final  String  BUCKET_PATH = "https://qy183-bucket-666.oss-cn-wuhan-lr.aliyuncs.com/";
    // 填写RAM用户的Access Key ID和Access Key Secret
    private static  final   String ACCESS_KEY_ID = "LTAI5tEx33Xd5bf6iL2pTM9o";
    private static  final  String ACCESS_KEY_SECRET = "SGP5fBX9ywIlf2uHkuTjibmU9zkCZU";
    // 填写Bucket名称
    private static  final  String BUCKET_NAME = "qy183-bucket-666";

    /**
     * 文件上传通用方法
     * @param filePath  文件要存放的路径，可以调用时随意指定  aaaa/bbbb
     * @param multipartFile   springmvc中封装要上传的文件对象
     * @return
     */
    public static Map uploadFile(String filePath, MultipartFile multipartFile){
        InputStream inputStream = null;
        OSS ossClient = null;
        try {
            //从springmvc 封装上传文件的对象中获取当前文件的原始的名字
            //  originalFilename = aaa.png     / 03bb049231d8480d92f48e819977c3d9_1560973053.png
            String originalFilename = multipartFile.getOriginalFilename();
            // 获取源文件名字的后缀
            String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));

            // 使用DefaultCredentialProvider方法直接设置AK和SK  多态
            CredentialsProvider credentialsProvider = new DefaultCredentialProvider(ACCESS_KEY_ID, ACCESS_KEY_SECRET);
            // EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
            //String bucketName = "qy183-bucket-001";
            // 填写Object完整路径，完整路径中不能包含Bucket名称，例如exampledir/exampleobject.txt。
            // 上传之后的文件的名字和路径  相对于bucket位置
            // objectName = aaaa/bbbb/f33017db-d471-4065-927e-1a6aa5b7e587.png
            String objectName = filePath+"/"+ UUID.randomUUID().toString() +suffix;
            // 填写本地文件的完整路径，例如D:\\localpath\\examplefile.txt。
            // 如果未指定本地路径，则默认从示例程序所属项目对应本地路径中上传文件流。
            //String filePath= "E:\\qy183\\aaa.txt";
            // 填写Bucket所在地域。以华东1（杭州）为例，Region填写为cn-hangzhou。
            String region = "cn-wuhan-lr";

            // 创建OSSClient实例。
            // 当OSSClient实例不再使用时，调用shutdown方法以释放资源。
            ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
            clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
            ossClient = OSSClientBuilder.create()
                    .endpoint(END_POINT)
                    .credentialsProvider(credentialsProvider)
                    .clientConfiguration(clientBuilderConfiguration)
                    .region(region)
                    .build();



            //实例化文件输入流
//            inputStream = new FileInputStream(filePath);
            inputStream = multipartFile.getInputStream();
            // 创建PutObjectRequest对象。
            PutObjectRequest putObjectRequest = new PutObjectRequest(BUCKET_NAME, objectName, inputStream);
            // 创建PutObject请求。
            PutObjectResult result = ossClient.putObject(putObjectRequest);
            //System.out.println("上传成功");
            //实例化返回值
            Map map = new HashMap();
            //BUCKET_PATH+objectName = https://qy183-bucket-001.oss-cn-wuhan-lr.aliyuncs.com/aaaa/bbbb/f33017db-d471-4065-927e-1a6aa5b7e587.png
            map.put("filePath",BUCKET_PATH+objectName);  //filePath上传后文件的路径  最终要保存数据库
            map.put("originName",originalFilename);  //原始文件的名字 最终要保存数据库
            return map;
        } catch (Exception e){
            e.printStackTrace();
        }finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
            try {
                if(inputStream!=null){
                    inputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }
}
